import 'dart:async';

import 'package:flutter/cupertino.dart';

import '../../../utils/Tools.dart';

class CustomCountdownTimer extends StatefulWidget {
  final DateTime endTime;
  final VoidCallback onEnd;

  const CustomCountdownTimer({
    super.key,
    required this.endTime,
    required this.onEnd,
  });

  @override
  CustomCountdownTimerState createState() => CustomCountdownTimerState();
}

class CustomCountdownTimerState extends State<CustomCountdownTimer> {
  Timer? _timer;
  late Duration _remainingTime;

  @override
  void initState() {
    super.initState();
    _remainingTime = _calculateRemainingTime();
    _startTimer();
  }

  Duration _calculateRemainingTime() {
    final now = DateTime.now();
    return widget.endTime.isAfter(now) ? widget.endTime.difference(now) : Duration.zero;
  }

  void _startTimer() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      final remainingTime = _calculateRemainingTime();
      if (remainingTime == Duration.zero) {
        _timer?.cancel();
        widget.onEnd();
      }
      setState(() {
        _remainingTime = remainingTime;
      });
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final minutes = _remainingTime.inMinutes.remainder(60).toString().padLeft(2, '0');
    final seconds = _remainingTime.inSeconds.remainder(60).toString().padLeft(2, '0');

    TextStyle textStyle = TextStyle(
      fontSize: 10,
      fontWeight: FontWeight.normal,
      color: Tools.fromHex("#F83F2D"),
    );

    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(minutes, style: textStyle),
        Text("分", style: textStyle),
        Text(seconds, style: textStyle),
        Text("秒", style: textStyle),
      ],
    );
  }
}
